package cn.kgc.springboot.vue.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.math.Calculator;
import cn.hutool.core.util.IdUtil;
import cn.kgc.springboot.vue.response.ResponseResult;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 课工场
 * @date 2024/12/19
 * @description
 */
@RestController
@RequestMapping("captcha")
// @CrossOrigin   //   类中的接口允许跨域访问
public class CaptchaController {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public ResponseResult  createCaptcha(){

        // 调用hutool工具包
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 45);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator(1));
        // 重新生成code
        captcha.createCode();
        // 验证码的计算结果
        double conversion = Calculator.conversion(captcha.getCode());
        // 图片转base64
        String imageBase64 = captcha.getImageBase64();
        // uuid
        String uuid = IdUtil.simpleUUID();
        // 存储验证码到redis缓存
        stringRedisTemplate.opsForValue().set(uuid,conversion+"",5, TimeUnit.MINUTES);

        return ResponseResult.success().data("img",imageBase64).data("uuid",uuid);
    }

}
